﻿using PLCWpfTest.Common;
using PLCWpfTest.Models;
using System.Threading.Tasks;
using YWM.Common.Exceptions;

namespace PLCWpfTest.ViewModels
{
    public class ParameterUpdateViewModel : BaseViewModel
    {
        public ParameterModel Parameter { get; set; }

        public ParameterUpdateModel ParameterUpdate { get; set; }

        public ParameterUpdateViewModel(ParameterModel parameter)
        {
            Parameter = parameter;
            ParameterUpdate = new ParameterUpdateModel { Value = parameter.Value };
            LoadCommand.UnexecutedFriendlyException += LoadCommand_UnexecutedFriendlyException;
        }

        protected override async Task LoadCommand_Executing(object parameter)
        {
            bool isOk = Parameter.IsHigh ? ParameterUpdate.Value > Parameter.CompareValue : ParameterUpdate.Value < Parameter.CompareValue;
            if (!isOk)
            {
                ParameterUpdate.Error = Parameter.WaringText;
                return;
            }
            ParameterUpdate.Error = string.Empty;
            await CommunicationCache.UpdateParameter(Parameter.Id, ParameterUpdate.Value.ToString());
            RaiseRequestClose();
        }

        private void LoadCommand_UnexecutedFriendlyException(FriendlyException ex)
        {
            ParameterUpdate.Error = ex.Message;
        }
    }
}
